#!coding:utf-8
# vim: tabstop=4 shiftwidth=4 softtabstop=4
"""
    @author join.kang
"""
from ConfigParser import ConfigParser
from django.db import transaction
import os
from rest_framework.response import Response
from cvirt.manager.models import Setting
from cvirt.manager.serializers import SettingSerializer

from cvirt.manager.views import BaseListAPIView, NamedAPIViewMixIn


class GlobalConfigList(NamedAPIViewMixIn, BaseListAPIView):
    model = Setting
    serializer_class = SettingSerializer

    def _get(self, request, *args, **kwargs):
        settings = Setting.objects.all()
        if not settings:
            settings = self.importsettings()

        serializer = SettingSerializer(settings,many=True)
        return Response(serializer.data)

    # @transaction.commit_on_success
    def importsettings(self):
        """if not setting items then import items of cvirt.conf into database"""
        filepath = "/etc/cvirt/cvirt.conf"
        if not os.path.exists(filepath):
            filepath = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))),'conf','cvirt.conf')
        conf = ConfigParser()
        conf.read(filepath)
        items = []
        sections = conf.sections()
        for s in sections:
            items += conf.items(s)

        for item in items:
            itemvalue = "None" if not item[1] else item[1]
            try:
                Setting.objects.create(name=item[0],value=itemvalue)
            except:
                pass

        settings = Setting.objects.all()
        return  settings


    @transaction.commit_on_success
    def _do_update(self,datas):
        for data in datas:
            Setting.objects.filter(name=data.get('name')).update(value=data.get("value"))

    def updatesettings(self,request,*args,**kwargs):
        try:
            self._do_update(request.DATA)
        except:
            pass

        settings = Setting.objects.all()
        serializer = SettingSerializer(settings,many=True)
        return Response(serializer.data)


if __name__ == "__main__":
    filepath = "/etc/cvirt/cvirt.conf"
    if not os.path.exists(filepath):
        filepath = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))),'conf','cvirt.conf')
    conf = ConfigParser()
    conf.read(filepath)
    sections = conf.sections()
    for s in sections:
        items = conf.items(s)
        for item in items:
            print item